// miniprogram/pages/NX_detailUser/detailUser.js
import configGantt, { getLocalString, getDate, ONE_DAY } from '../../library/configGantt'
const db = wx.cloud.database();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        options: {
            master: false,
            userId: '',
            projectId: '',
            role: ''
        },
        userInfo: null,
        projectInfo: null,
        mission: null,
        gantt: null,
        ganttInit: false,
        missionDoing: [],
        missionDelay: [],
        code: null,
        role: null,
        self: false,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        options.master = options.master === 'true'
        this.setData({ options });
        this.init();
    },
    init() {
        const options = this.data.options;
        //抓取用户信息
        db.collection('user').doc(options.userId).get().then(res => {
            this.setData({
                userInfo: res.data,
                self: res.data._id === getApp().globalData.userInfo._id
            })
        })
        db.collection('code').field({
            role: true,
            code:true
        }).where({
            userId: options.userId,
            group: options.projectId
        }).get().then(res => {
            if (res.data && res.data.length > 0) {
                this.setData({
                    role: res.data[0].role || 'user',
                    code: res.data[0]
                })
            }
        })
        //抓取项目信息
        if (options.projectId) {
            db.collection('group').doc(options.projectId).field({
                project: true
            }).get().then(res => {
                this.setData({
                    projectInfo: res.data
                })
            })
        }
        //抓取任务信息
        db.collection('mission').field({
            _id: true
        }).where({
            projectId: options.projectId,
            userId: options.userId
        }).get().then(res => {
            const mission = []
            Promise.all(res.data.map(item => {
                return new Promise(resolve => {
                    wx.cloud.callFunction({
                        name: 'getMissionInfo',
                        data: {
                            id: item._id
                        }
                    }).then(res => {
                        mission.push(res.result)
                        resolve();
                    })
                })
            })).then(() => {
                this.setData({
                    mission
                })
                //过滤任务
                const initedMission = []
                const today = new Date().getTime();
                const missionDoing = [], missionDelay = []
                for (const item of mission) {
                    if (item.init) initedMission.push(item);
                    const start = getDate(item.start).getTime();
                    const end = getDate(item.end).getTime() + ONE_DAY;
                    if (start <= today && end >= today) {
                        missionDoing.push(item)
                    } else if (end <= today && item.status !== 'done') {
                        missionDelay.push(item)
                    }

                }
                this.setData({
                    missionDoing,
                    missionDelay
                })
                configGantt(initedMission, 80, {
                    mix: true
                }).then(gantt => {
                    if (gantt && gantt.ganttList && gantt.ganttList.length) {
                        this.setData({
                            gantt,
                            ganttInit: true
                        })
                    }
                })
            })
        })
    },
    fireMember() {
        wx.showModal({
            title: '提示',
            content: '请离操作无法还原，是否确定？',
            success: res => {
                if (res.confirm) {
                    wx.showLoading({
                        title: '操作中',
                        mask: true,
                    })
                    wx.cloud.callFunction({
                        name: 'delCode',
                        data: {
                            code:this.data.code.code,
                            groupId:this.data.options.projectId,
                            userId:this.data.options.userId,
                            operator: getApp().globalData.userInfo._id
                        }
                    }).then(() => {
                        wx.hideLoading();
                        wx.navigateBack({
                            delta: 1
                        })
                    }).catch(err => {
                        console.log(err);
                        wx.hideLoading();
                        wx.showToast({
                            title: '操作失败，请重试',
                            icon: 'nonce'
                        })
                    })
                }
            }
        })
    },
    setRole() {
        const itemList = [];
        switch (this.data.role) {
            case 'master':
                itemList.push('设为一般用户');
                break;
            case 'user':
            default:
                itemList.push('设为管理员');
        }
        wx.showActionSheet({
            itemList,
            success: res => {
                if (res.tapIndex === 0) {
                    let role = '', roleName = '';
                    switch (this.data.role) {
                        case 'master':
                            role = 'user';
                            roleName = '一般用户';
                            break;
                        case 'user':
                        default:
                            role = 'master';
                            roleName = '管理员';
                    }
                    wx.showModal({
                        title: '确认',
                        content: `确认将 ${this.data.userInfo.userName} 在项目【${this.data.projectInfo.project.projectName}】中设为${roleName}吗`,
                        success: res => {
                            if (res.confirm) {
                                wx.cloud.callFunction({
                                    name: 'updateCodeInfo',
                                    data: {
                                        codeId: this.data.code._id,
                                        role
                                    }
                                }).then(() => {
                                    this.init();
                                    wx.showToast({
                                        title: '操作成功'
                                    })
                                })
                            }
                        }
                    })
                }
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

})